const db = uniCloud.database()
const courseDBName = 'mydb-course-list'
const courseCatDBName = 'mydb-course-categories'
const uniID = require('uni-id-common')
const uniqueJSON=function(arr, attrName) {
      let result = arr.filter((item, index, self) => {
        return index === self.findIndex((t) => (t[attrName] === item[attrName]));
      });
      console.log("原json数组: ", arr);
      console.log("去重结果: ", result);
      return result;
    }
module.exports = {
	_before: async function () { // 通用预处理器
		this.startTime = Date.now()
		//客户端信息
		const clientInfo = this.getClientInfo()
		this.dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
			clientInfo,
		})
		this.uniIdCommon = uniID.createInstance({
			clientInfo: this.getClientInfo()
		})
		const {
			errCode,
			errMsg,
			uid
		} = await this.uniIdCommon.checkToken(this.getUniIdToken())
		console.log('errCode',errCode)
		if(errCode) { // uni-id-common的checkToken接口可能返回`uni-id-token-expired`、`uni-id-check-token-failed`错误码，二者均会触发客户端跳转登陆页面
			return {
				errCode,
				errMsg
			}
		}else{
			this.uid=uid
		}
	},
	/**
	 * getHomeConfig获取首页数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getHomeConfig(param1) {

		let basics = {},banner=[],diys=[]
		basics = await db.collection(courseDBName).where({article_status:1,category_id:'67092e1521821bdf939ac115'}).get()
		diys = await db.collection(courseDBName).where({article_status:1,category_id:'6720914d86206611b4c6c3cf'}).get()
		banner = await db.collection('opendb-banner').where({status:true}).get()
		banner=banner.data.map((item)=>item.bannerfile.url)
		return {
			banner,
			menuData: [
			  {
			    title: '课程体系',
			    icon: 'tn-icon-calendar',
			    color: 'tn-bg-orange',
			    value: '我就看看',
				url:'/pages/list/list?category_id=670f208cfe975f276682f2a0'
			  },
			  {
			    title: '优秀讲师',
			    icon: 'tn-icon-trophy',
			    color: 'tn-bg-bluepurple',
			    value: '我就看看',
				url:'/pages/list/list?category_id=670f0e2b0d2b31998ce0c62a'
			  },
			  {
			    title: '最新课程',
			    icon: 'tn-icon-company',
			    color: 'tn-bg-indigo',
			    value: '我就看看',
				url:'/pages/course/course'
			  },
			  {
			    title: '课程排行',
			    icon: 'tn-icon-comment',
			    color: 'tn-bg-purplered',
			    value: '我就看看',
				url:'/pages/course/course'
			  }
			],
			tuniaoData: [
			  {
			    title: '热门专栏',
			    icon: 'fire-fill',
			    color: 'red',
			    value: '我就看看'
			  },
			  {
			    title: '优秀讲师',
			    icon: 'praise-fill',
			    color: 'blue',
			    value: '我就看看'
			  },
			  {
			    title: '必看攻略',
			    icon: 'cardbag-fill',
			    color: 'orange',
			    value: '我就看看'
			  },
			  {
			    title: '课程排行',
			    icon: 'honor-fill',
			    color: 'purple',
			    value: '我就看看'
			  }
			],
			basics:{
				data:basics.data,
				cid:'67092e1521821bdf939ac115',
				title:'优选课程'
			},
			diys:{
				data:diys.data,
				cid:'6720914d86206611b4c6c3cf',
				title:'动漫课程'
			}
		}
	},
	/**
	 * getUserData获取个人中心数据
	 * @param {string} param1 参数1描述getranks
	 * @returns {object} 返回值描述
	 **/
	async getUserData(){
		let score=0,days=0,words=0
		if(this.uid){
			let scoreRes=await db.collection('uni-id-scores').where({
				user_id:this.uid
			}).orderBy("create_date", "desc").limit(1).get()
			let catchRes=await db.collection('mydb-course-catch').where({
				user_id:this.uid
			}).orderBy("create_date", "desc").limit(1).get()
			console.log('scoreRes',scoreRes)
			score=scoreRes.data && scoreRes.data.length ? scoreRes.data[0]['balance'] : 0
			days=catchRes.data && catchRes.data.length ? catchRes.data[0]['days'] : 1
			words=25
		}
		return {
			code:1,
			data:{
				score,
				days,
				words
			}
		}
	},
	/**
	 * getCourseDetail获取课程数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getCourseDetail(id) {
		let res = {};
		res = await db.collection(courseDBName).doc(id).get()
		return res.data[0] ? {
			code : 1,
			data : res.data[0]
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getCourseDetail获取课程数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getCourseCatch(course_id) {
		let result = {};
		result = await db.collection('mydb-course-catch').where({
			course_id,
			user_id:this.uid
		}).get()
		console.log('result',result)
		return result.data[0] ? {
			code : 1,
			data : result.data[0]
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getCourseList获取课程数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getCourseAll(where={}) {
		const result = await this.dbJQL.collection(courseDBName).where({
			article_status:1,
			...where
		}).get()
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getCourseList获取课程数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getCourseList(course_id) {
		console.log('params',{
			user_id:this.uid,
			course_id
		})
		const result = await this.dbJQL.collection('mydb-course-catch').where({
			user_id:this.uid,
			course_id
		}).get()
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getCourseChapter获取课时数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getCourseChapter(course_id) {

		const result = await this.dbJQL.collection('mydb-course-chapter').where({
			course_id
		}).get()
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getChapterDetail获取课时数据
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getChapterDetail(_id) {
		console.log('_id',_id)
		const result = await this.dbJQL.collection('mydb-course-chapter').doc(_id).get()
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getChapterWords获取课时学习单词
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getChapterStudyWords(chapter_id,limit=20) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const result = await this.dbJQL.collection('mydb-course-unit').where(params).limit(limit).get()
		return result.data.length ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	
	
	/**
	 * getChapterSentences获取章节逐句精听
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getChapterSentences(chapter_id,limit=5) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const result = await this.dbJQL.collection('mydb-course-sentence').where(params).limit(limit).get()
		return result.data.length ? {
			code : 1,
			data : result.data[0]
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getChapterWords获取完形填空学习单词
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getChapterFillSentence(chapter_id,type=1,limit=20) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const wordsUse = await this.dbJQL.collection('mydb-course-unit').where(params).limit(limit).get()
		const words=wordsUse.data.map((item)=>item.word)
		let result=[]
		wordsUse.data.forEach((item,index)=>{
			let i=index
			let selectWords=wordsUse.data.filter((op)=>op.word!=item.word)
			selectWords=selectWords.sort(() => Math.random() - 0.5);
			let selectOptions=[{
				word:item.word,
				name:item.explain
			},{
				word:selectWords[0]['word'],
				name:selectWords[0].explain
			},{
				word:selectWords[1]['word'],
				name:selectWords[1].explain
			},{
				word:selectWords[2]['word'],
				name:selectWords[2].explain
			}]
			selectOptions=selectOptions.sort(() => Math.random() - 0.5);
			result.push({
				imgfile:item.imgfile,
				word:item.word,
				sentence:item.example,
				options:[selectOptions[0],selectOptions[1],selectOptions[2],selectOptions[3]]
			})
		})
		console.log('result',result)
		return result.length ? {
			code : 1,
			data : result
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	async getChapterTestSentence(chapter_id,type=1,limit=20) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const wordsUse = await this.dbJQL.collection('mydb-words-sentence').where(params).limit(limit).get()
		console.log('result',wordsUse.data)
		return wordsUse.data.length ? {
			code : 1,
			data : wordsUse.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getTestWords获取测试
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getTestWords(type=1,limit=20) {
		let params={status:true}
		const wordsUse = await this.dbJQL.collection('mydb-course-unit').where(params).limit(limit).get()
		console.log('wordsUse.data',wordsUse.data)
		const words=wordsUse.data.map((item)=>item.word)
		let result=[]
		wordsUse.data.forEach((item,index)=>{
			let i=index
			let selectWords=wordsUse.data.filter((op)=>op.word!=item.word)
			selectWords=selectWords.sort(() => Math.random() - 0.5);
			let explains=[
				item.explain,
				selectWords[0]['explain'],
				selectWords[1]['explain'],
				selectWords[2]['explain']
			]
			explains=explains.sort(() => Math.random() - 0.5);
			result.push({
				imgfile:item.imgfile,
				word:item.word,
				explain:item.explain,
				explains:[explains[0],explains[1],explains[2],explains[3]]
			})
		})
		console.log('result',result)
		return result.length ? {
			code : 1,
			data : result
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getChapterWords获取单词记词义
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getChapterWords(chapter_id,limit=20,type=1) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const wordsUse = await this.dbJQL.collection('mydb-course-unit').where(params).limit(limit).get()
		const words=wordsUse.data.map((item)=>item.word)
		let result=[]
		wordsUse.data.forEach((item,index)=>{
			let i=index
			let selectWords=wordsUse.data.filter((op)=>op.word!=item.word)
			selectWords=selectWords.sort(() => Math.random() - 0.5);
			let explains=[
				item.explain,
				selectWords[0]['explain'],
				selectWords[1]['explain'],
				selectWords[2]['explain']
			]
			explains=explains.sort(() => Math.random() - 0.5);
			result.push({
				imgfile:item.imgfile,
				word:item.word,
				explain:item.explain,
				explains:[explains[0],explains[1],explains[2],explains[3]]
			})
		})
		console.log('result',result)
		return result.length ? {
			code : 1,
			data : result
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	/**
	 * getChapterExplains获取词义记单词
	 * @param {string} chapter_id 章节
	 * @param {string} type 类型
	 * @returns {object} 返回值描述
	 **/
	async getChapterExplains(chapter_id,type=3,limit=20,) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const wordsUse = await this.dbJQL.collection('mydb-course-unit').where(params).limit(limit).get()
		const words=wordsUse.data.map((item)=>item.explain)
		let result=[]
		wordsUse.data.forEach((item,index)=>{
			let i=index
			let selectWords=wordsUse.data.filter((op)=>op.explain!=item.explain)
			selectWords=selectWords.sort(() => Math.random() - 0.5);
			let explains=[
				item.word,
				selectWords[0]['word'],
				selectWords[1]['word'],
				selectWords[2]['word']
			]
			explains=explains.sort(() => Math.random() - 0.5);
			result.push({
				word:type==3?item.explain:item.explainEn,
				imgfile:item.imgfile,
				explain:item.word,
				explains:[explains[0],explains[1],explains[2],explains[3]]
			})
		})
		console.log('result',result)
		return result.length ? {
			code : 1,
			data : result
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	
	/**
	 * getChapterWords获取听力单词
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getChapterListenWords(chapter_id,limit=5) {
		let params={status:true}
		chapter_id && (params['chapter_id']=chapter_id)
		const wordsAll = await this.dbJQL.collection('mydb-course-unit').where({status:true}).get()
		const wordsUse = await this.dbJQL.collection('mydb-course-unit').where(params).limit(limit).get()
		const words=wordsUse.data.map((item)=>item.word)
		console.log('wordsUse',wordsUse)
		let result=[]
		let selectWords=wordsAll.data.sort(() => Math.random() - 0.5);
		selectWords=selectWords.filter((op)=>!words.includes(op.word))
		console.log('selectWords',selectWords)
		wordsUse.data.forEach((item,index)=>{
			let i=index
			let selects=[
				item.word,
				selectWords[i+1]['word'],
				selectWords[i+2]['word'],
				selectWords[i+3]['word']
			]
			selects=selects.sort(() => Math.random() - 0.5);
			result.push({
				word:item.word,
				explain:item.explain,
				explainEn:item.explainEn,
				audiofile:item.audiofile,
				selectOptions:[selects[0],selects[1],selects[2],selects[3]]
			})
		})
		return result.length ? {
			code : 1,
			data : result
		} : {
			msg : '暂无数据',
			code: 0
		}
	
	},
	
	async getTestList(){
		const result = await this.dbJQL.collection('mydb-words-test').where({
			user_id:this.uid
		}).get()
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	async getTestDetail(id,type){
		const result = await this.dbJQL.collection('mydb-words-test').doc(id).get()
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data[0]
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	async delTest(id){
		const result = await this.dbJQL.collection('mydb-words-test').doc(id).remove()
		console.log('result',result)
		return result ? {
			code : 1,
			data : result
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	async submitProgress(params,action='add'){
		const result = action=='add' ? await this.dbJQL.collection('mydb-course-progress').add({
			...params,
			user_id:this.uid,
			publish_date:new Date().getTime()
			}) : await this.dbJQL.collection('mydb-course-progress').where({
			chapter_id:params.id,
			user_id:this.uid
		}).update({
			progress: params.progress,
			last_modify_date:new Date().getTime()
		})
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	// 单词量测试保存
	async submitScore(params,action='add'){
		const result = action=='add' ? await this.dbJQL.collection('mydb-words-test').add({...params}) : 
		await this.dbJQL.collection('mydb-words-test').doc(params.id).update({
			answer:params.answer,
			progress: params.progress,
			score:params.score,
			content: params.content
		})
		console.log('result',result)
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	// 获取排名
	async getranks(params){
		const result = await this.dbJQL.collection('mydb-words-test,uni-id-users').field('progress,score,user_id.nickname,user_id.avatar,user_id._id,user_id.avatar_file').orderBy('score').get()
		let data=result.data.map((item)=>{
			console.log(item)
			return {
				progress:item.progress,
				score:item.score,
				uid:item.user_id.length ? item.user_id[0]['_id'] :'——',
				user_id:item.user_id
			}
		})
		console.log(data)
		data=uniqueJSON(data,'uid')
		return data ? {
			code : 1,
			data
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	async getUserLog(params){
		const result = await this.dbJQL.collection('mydb-course-progress').where({
			user_id:this.uid
		}).get()
		return result.data ? {
			code : 1,
			data : result.data
		} : {
			msg : '暂无数据',
			code: 0
		}
	},
	/**
	 * getShareContent获取分享内容
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 **/
	async getShareContent(chapter_id) {
		return{
			code : 1,
			data : {
				title: 'Good Job',
				imageUrl: 'https://mp-e3fbd118-dad0-4878-b40b-44597e7aa0eb.cdn.bspapp.com/icons/一小撮花.png',
				desc: '单词学习打打卡',
				content: '我今天学习了20个单词，你也一起来呀'
			}
		} 
	
	},
	
}
